<?php
$shortopts = 't:';
$options   = getopt($shortopts);

if(!isset($options['t'])) {
    die("t options required\n");
}

if($options['t'] == 'transproducer') {
    try { 
        $transactionProducer = new Rocketmq\TransactionProducer;
    } catch (Exception $e) {
        var_dump($e);    
    } 

    $transactionProducer->setProducerGroup("group_name_2");
    $transactionProducer->start();

    $limit = 10;
    while ($limit--) {

        try {
            $t1 = microtime(true);
            $ret = $transactionProducer->sendMessageInTransaction('TopicTest', 'tagA', 'key1', "messaged $limit");
            $t2 = microtime(true);

            //$a['send_'.$limit] = $t2 - $t1;

            $transactionProducer->endTransaction($ret->getMsgId(), 0);

            echo $limit . ': ' . $ret->getMsgId() . ': ' . $ret->getUniqKey() . PHP_EOL;

        } catch (Exception $e) {
            var_dump($e->getMessage());    
        }

        $limit--;
        if($limit <= 0) {
            $limit = 50;
            usleep(1000*300);
        }
    }

    //print_r($a);
    //var_dump(array_sum($a)/count($a));
    exit;
}
elseif($options['t'] == 'producer') {
    try {
        $Producer = new Rocketmq\Producer;
    } catch (Exception $e) {
        var_dump($e);    
    }

    $Producer->setProducerGroup("group_name_1");
    $Producer->start();

    $limit = 10;
    $a = [];
    while ($limit--) {

        try {
            $t1 = microtime(true);
            $ret = $Producer->send('TopicTest', 'tagA', 'key1', "message $limit");
            $t2 = microtime(true);

            $a['send_'.$limit] = $t2 - $t1;

            echo $limit . ': ' . $ret->getMsgId() . PHP_EOL;
        } catch (Exception $e) {
            var_dump($e->getMessage());   
        }

        $limit--;
        if($limit <= 0) {
            $limit = 50;
            usleep(1000*300);
        }
        
    }

    print_r($a);
    exit;
}
elseif($options['t'] == 'consumer') {
    $pushConsumer = new Rocketmq\pushConsumer();
    $consumerGroupName = "please_rename_unique_group_name_4";
    $topic = "TopicTest";
    $tags = "*";
    $pushConsumer->setConsumerGroup($consumerGroupName);
    $pushConsumer->subscribe($topic, $tags, "consume");
    $pushConsumer->start();

    sleep(54324320);
}

function consume($msg) {
    static $count = 0;

    echo "$count ";
    echo ": PHP Code: ";
    echo $msg->getTopic() . ', ';
    echo $msg->getMsgId() . ', ';
    echo date("Y-m-d H:i:s", $msg->getBornTimestamp()/1000) . ', ';
    echo date("Y-m-d H:i:s", $msg->getStoreTimestamp()/1000) . ', ';
    echo $msg->getPreparedTransactionOffset() . ', ';
    echo $msg->getProperty('UNIQ_KEY') . ', ';
    echo $msg->getCommitLogOffset() . ', ';
    echo $msg->getBody();
    echo PHP_EOL;

    $count++;

    return 0;
}
